import random
import backtrader as bt
from loguru import logger
import numpy as np
from .boll_m import CustomBollingerBands  # 新增导入

class RandomPrintStrategy(bt.Strategy):
    def __init__(self):
        self.stocks=[]
        for i in range(0, len(self.datas),2):
            stock= self.datas[i]
            self.stocks.append(stock)
            stock.weekly=self.datas[i+1]

        self.next_count = 0
        self.prenext_count = 0
        self.last_date = None

        logger.info(f"策略初始化完成，共加载 {len(self.stocks)} 只股票")
        # 为每个stock添加布林带指标和MACD指标
        for data in self.stocks:

            data.bollm = CustomBollingerBands(data)
            # 使用backtrader自带的BollingerBands计算weekly_bollm
            data.weekly_bollm = bt.indicators.BollingerBands(data.weekly)
            data.weekly_macd = bt.indicators.MACD(
                data.weekly,
                period_me1=12,  # 快线周期
                period_me2=26,  # 慢线周期
                period_signal=9  # 信号线周期
            )
            # 只在数据充足时添加MACD指标
            data.macd = bt.indicators.MACD(
                data,
                period_me1=12,  # 快线周期
                period_me2=26,  # 慢线周期
                period_signal=9  # 信号线周期
            )

    def work(self):
        """随机选股并打印逻辑"""
        dt = self.datas[0].datetime.date(0)
        # 每天只打印一次
        if self.last_date == dt:
            return
        self.last_date = dt
        max_attempts = len(self.stocks)
        for attempt in range(max_attempts):
            data = random.choice(self.stocks)
            if len(data) > 0:
                # 获取布林带指标
                boll = data.bollm
                logger.debug(f"{dt} 随机股票: {data._name}, close: {data.close[0]}")
                logger.debug(f"  BOLL指标: mida={boll.lines.mida[0]:.2f}, uppera={boll.lines.uppera[0]:.2f}, lowera={boll.lines.lowera[0]:.2f}, bb={boll.lines.bb[0]:.2f}, mb={boll.lines.mb[0]:.2f}, boll={boll.lines.boll[0]:.2f}, ub={boll.lines.ub[0]:.2f}, lb={boll.lines.lb[0]:.2f}")

                                    
                try:
                    # 检查MACD指标是否存在且有有效数据
                    if data.macd is not None:
                        macd = data.macd
                        if len(macd.macd) > 0 and len(macd.signal) > 0:
                            logger.debug(f"  MACD指标: macd={macd.macd[0]:.4f}, signal={macd.signal[0]:.4f}, result={2*(macd.macd[0]-macd.signal[0]):.4f}")
                    else:
                        logger.debug(f"  MACD指标: 未添加（数据量不足）")

                    weekly=data.weekly
                    logger.debug(f"weekly timestamp: {weekly.datetime.date(0)},weekly open: {weekly.open[0]}, weekly close: {weekly.close[0]}")
                    weekly_boll = data.weekly_bollm
                    logger.debug(f"weekly_boll: mid={weekly_boll.lines.mid[0]:.2f}, top={weekly_boll.lines.top[0]:.2f}, bot={weekly_boll.lines.bot[0]:.2f}")
                    weekly_macd=data.weekly_macd
                    logger.debug(f"weekly_macd: {weekly_macd.macd[0]:.4f}, signal={weekly_macd.signal[0]:.4f}, result={2*(weekly_macd.macd[0]-weekly_macd.signal[0]):.4f}")

                    return

                except Exception as e:
                    logger.error(f"{dt} 计算指标时出错: {e}")
                    return
            else:
                logger.warning(f"{dt} 股票 {data._name} 没有数据")
        logger.warning(f"{dt} 所有股票都没有数据")

    def prenext(self):
        self.prenext_count += 1
        if self.prenext_count <= 5:
            dt = self.datas[0].datetime.date(0)
            available_stocks = [data for data in self.stocks if len(data) > 0]
            logger.debug(f"{dt} prenext - 可用股票数量: {len(available_stocks)}/{len(self.stocks)}")
            not_available_stocks = [data._name for data in self.stocks if len(data) == 0]
            logger.warning(f"{dt} 没有数据的股票: {not_available_stocks}")
        if self.prenext_count % 100 == 0:
            dt = self.datas[0].datetime.date(0)
            available_stocks = [data for data in self.stocks if len(data) > 0]
            logger.info(f"{dt} prenext统计 - 已调用 {self.prenext_count} 次，当前可用股票: {len(available_stocks)}/{len(self.stocks)}")
        self.work()

    def next(self):
        self.next_count += 1
        if self.next_count % 100 == 0:
            dt = self.datas[0].datetime.date(0)
            logger.info(f"{dt} next统计 - 已调用 {self.next_count} 次")
        self.work()
    
    def stop(self):
        logger.info(f"策略执行完成 - prenext调用: {self.prenext_count} 次, next调用: {self.next_count} 次") 